//The MIT License (MIT)
//
// Copyright (c) Harry
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package com.ruoyi.web.controller.system;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.IpUtils;
import com.ruoyi.system.domain.DownloadHistory;
import com.ruoyi.system.service.IDownloadHistoryService;
import com.ruoyi.web.core.config.ApkFileFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author: Harry
 * @date: 2023-12-12 20:04
 * @desc: DownloadController
 */
@Controller
@RequestMapping("/download/latest")
public class DownloadController {

    @Autowired
    private IDownloadHistoryService downloadHistoryService;

    /**
     * 下载apk
     */
    @GetMapping()
    @ResponseBody
    public AjaxResult download(HttpServletRequest request, HttpServletResponse response) throws IOException {
        DownloadHistory history = new DownloadHistory();
        history.setDownloadIp(IpUtils.getIpAddr(request));
        history.setDeviceInfo(getMobileDevice(request));
        downloadHistoryService.insertDownloadHistory(history);

        File fileP = FileUtil.file(new ApplicationHome().getDir().toString() + "/download");

        if (!fileP.exists()) {
            return AjaxResult.error("下载文件不存在");
        }
        File[] apks = fileP.listFiles(new ApkFileFilter());

        if (apks == null) {
            return AjaxResult.error("下载文件不存在");
        }

        // BufferedInputStream inputStream = FileUtil.getInputStream(file);
        // ServletOutputStream os = response.getOutputStream();;
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) apks[0].length());
        response.setHeader("Content-Disposition", "attachment;filename=" + apks[0].getName());


        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(apks[0]));) {
            byte[] buff = new byte[1024];
            OutputStream os = response.getOutputStream();
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            return AjaxResult.error("下载失败");
        }
        return AjaxResult.error("下载成功");
    }

    public static String getMobileDevice(HttpServletRequest request) {
        String userAgent = request.getHeader("user-agent");
        String deviceStr = "";
        try {
            if (StrUtil.isNotEmpty(userAgent)) {
                int startIndex = userAgent.indexOf("(");
                int endIndex = userAgent.indexOf(")");
                deviceStr = userAgent.substring(startIndex + 1, endIndex);
                return deviceStr;
            }
        } catch (Exception e) {
        }
        return null;
    }
}
